package com.lh.music.fragment.localsong;


import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.OrientationHelper;
import android.support.v7.widget.RecyclerView;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.lh.music.IMusic.IMusic;
import com.lh.music.PlayApplication;
import com.lh.music.R;
import com.lh.music.adapter.RecyclAdapter;
import com.lh.music.constant.Constants;
import com.lh.music.dao.SongDao;
import com.lh.music.datamanager.DataManager;
import com.lh.music.entity.Song;
import com.lh.music.util.SampleDivider;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

/**
 * A simple {@link Fragment} subclass.
 */
public class DanquFragment extends Fragment implements RecyclAdapter.OnItemClickListener,RecyclAdapter.OnMoreClickListener {
    private RecyclerView recyclerView;
    private View view;
    private List<Song> mData = new ArrayList<>();
    private RecyclAdapter adapter;
    //音乐播放功能的接口
    private IMusic iMusic;
    //int position = 0;
    Timer timer;
    PopupWindow window;

    private SongDao dao;
    public DanquFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        if (view == null) {
            view = inflater.inflate(R.layout.fragment_danqu, container, false);
            recyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);
            LinearLayoutManager manager = new LinearLayoutManager(getActivity());
            manager.setOrientation(OrientationHelper.VERTICAL);
            recyclerView.setLayoutManager(manager);
            adapter = new RecyclAdapter(getActivity(), mData);
            dao=new SongDao(getActivity());
            adapter.setOnItemClickListener(this);
            adapter.setOnMoreClickListener(this);
            recyclerView.addItemDecoration(new SampleDivider(getActivity()));
            recyclerView.setAdapter(adapter);
            new MyTask().execute();

        }
        return view;
    }

    @Override
    public void onItemClickListener(Song song, int position) {

        //更新
        updateListView();
        //更换播放列表
        PlayApplication app= (PlayApplication) getActivity().getApplication();
        app.currentSongList.clear();
        app.currentSongList.addAll(mData);
        SongDao dao=new SongDao(getActivity());
        try {
            dao.updatePlaySongList(app.currentSongList);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        //跳转到所在的activity， 当前activity的启动模式为singleTop
       /* Intent activityIntent = new Intent(getActivity(), LocalSongActivity.class);
        activityIntent.putExtra("song", song);
        activityIntent.putExtra("state", Constants.PLAYING);
        activityIntent.putExtra("position", position);
        startActivity(activityIntent);*/

        //发送一个开始播放的广播  更换播放列表  将播放位置传过去
        Intent broadIntent = new Intent();
       /* Bundle bundle = new Bundle();
        ArrayList songList = (ArrayList) mData;
        bundle.putSerializable("songList", songList);
        broadIntent.putExtra("bundle", bundle);
        broadIntent.putExtra("position", position);
        broadIntent.setAction(Constants.PLAY_ACTION);*/
        broadIntent.putExtra("position", position);
        broadIntent.setAction(Constants.PLAY_ACTION);
        getActivity().sendBroadcast(broadIntent);
    }

    @Override
    public void onMoreClickListtener(Song song) {
        backgroundAlpha(0.4f);
        //弹出popupwindow
        initPopupWindow(song);
    }

    private void initPopupWindow(Song song) {
        View popupView=LayoutInflater.from(getActivity())
                .inflate(R.layout.popup_song,null);
        window=new PopupWindow(popupView,ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT );
        //更新window中的值
        updatePopupView(popupView,song);
        window.setFocusable(true);
        window.setOutsideTouchable(true);
        ColorDrawable colorDrawable=new ColorDrawable(0);
        window.setBackgroundDrawable(colorDrawable);
        //window消失之后的监听
        window.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                backgroundAlpha(1.0f);
            }
        });
        window.setAnimationStyle(R.style.popup_anim);
        //获取屏幕的高度   显示矩阵对象
        DisplayMetrics dm=new DisplayMetrics();
        getActivity().getWindowManager().getDefaultDisplay().getMetrics(dm);  //拿到屏幕的信息


        window.showAtLocation(popupView, Gravity.NO_GRAVITY,
                0,
                dm.heightPixels-popupView.getHeight());
    }

    private void updatePopupView(View popupView, final Song song) {
        TextView song_name= (TextView) popupView.findViewById(R.id.song_name);
        TextView artist_name= (TextView) popupView.findViewById(R.id.artist_name);
        TextView album_name= (TextView) popupView.findViewById(R.id.album_name);
        song_name.setText("歌曲："+song.getTitle());
        artist_name.setText("歌手："+song.getArtist());
        album_name.setText("专辑："+song.getAlbum());
        //将这首歌添加到我喜欢
        popupView.findViewById(R.id.add).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                boolean i= false;
                try {
                    i = dao.updateSongIsFavorate(song);
                } catch (SQLException e) {
                    e.printStackTrace();
                }
                if (i){
                    Toast.makeText(getActivity(), "添加成功", Toast.LENGTH_SHORT).show();
                }else{
                    Toast.makeText(getActivity(), "歌曲已经存在", Toast.LENGTH_SHORT).show();

                }
                window.dismiss();
            }
        });
    }

    //开启一个异步，用于加载本地歌曲
    class MyTask extends AsyncTask<Void, Void, Void> {
        @Override
        protected Void doInBackground(Void... params) {
            DataManager dataManager = new DataManager(getActivity());
            mData.addAll(dataManager.findAllSong());
            return null;
        }

        @Override
        protected void onPostExecute(Void list) {
            adapter.notifyDataSetChanged();
            //数据加载完之后，更新播放栏中的UI
            timerUpdateListView();
        }
    }
    private void updateListView(){
        PlayApplication app= (PlayApplication) getActivity().getApplication();

       for (int i=0;i<mData.size();i++){
           mData.get(i).setVisiable(false);
           //如果这首歌和正在播放的歌一样   该项显示小喇叭
           if (app.currentSong!=null){
               if (mData.get(i).getTitle().equals(app.currentSong.getTitle())){
                   mData.get(i).setVisiable(true);
               }
           }

       }
        adapter.notifyDataSetChanged();
    }
    protected Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            if (msg.what==1){
                updateListView();
            }
        }
    };
    private void timerUpdateListView(){
        timer=new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                Message msg=handler.obtainMessage();
                msg.what=1;
                handler.sendMessage(msg);
            }
        },0,400);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        timer.cancel();
    }
    /**
     * 设置添加屏幕的背景透明度
     * @param bgAlpha
     */
    public void backgroundAlpha(float bgAlpha)
    {
        WindowManager.LayoutParams lp = getActivity().getWindow().getAttributes();
        lp.alpha = bgAlpha; //0.0-1.0
        getActivity().getWindow().setAttributes(lp);
    }
}

